﻿<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <meta charset="utf-8" />
    <script src="js/html2canvas.js"></script>
    <script type="text/javascript" src="/print/js/jspdf.min.js"></script>
</head>
<body>
    <div class="print">
    <div class="btns" style="padding:5px 0">
        <input id="btn-Preview-PDF" onclick="javascript:demoFromHTML()" type="button" class="btn" value="PDF 预 览" />
        <input id="btn-Preview-Image" type="button" class="btn" value="预 览" />
        <a id="btn-Convert-Html2Image" href="#" class="btn">下载</a>
    </div>
    <div class="code-box">
        <div class="code-view">
            <h3>打印预览 :</h3>
            <div class="code-list" id="html-content-holder"></div>
        </div>
        <div class="preview">
            <h3>预 览 :</h3>
            <div id="previewImage">
            </div>
            <div id="previewPDF">
            </div>
        </div>
    </div>
</div>
    <link rel="stylesheet" href="/print/print.css?v=1.0.0" media="all">
    <script type="text/javascript" src="/print/jquery.min.js"></script>
    <script type="text/javascript" src="/print/qrcode.min.js"></script>
    <script type="text/javascript" src="/print/jquery-barcode.js"></script>
    <img id="downloadImg" height="250" th:src="123.png" />
    <button type="button" id=download>下载图片</button>
    <script>
        //--参考文档
        //-- https://www.cnblogs.com/y896926473/articles/8029090.html
        //-- http://caibaojian.com/js-download.html
        $("#download").click(function () {
            var img = document.getElementById('downloadImg'); // 获取要下载的图片
            var url = img.src;                                // 获取图片地址
            var a = document.createElement('a');              // 创建一个a节点插入的document
            var event = new MouseEvent('click')               // 模拟鼠标click点击事件
            a.download = '图片名称'                            // 设置a节点的download属性值,图片名称
            a.href = url;                                     // 将图片的src赋值给a节点的href
            a.dispatchEvent(event);
        })
        var type = GetQueryValue("type");//0--前五个，1--物品标签，2--位置标签
        var v1 = GetQueryValue("v1");
        var v2 = GetQueryValue("v2");
        var v3 = GetQueryValue("v3");
        var v4 = GetQueryValue("v4");
        var v5 = GetQueryValue("v5");
        var v6 = GetQueryValue("v6");
        var v7 = GetQueryValue("v7");
        console.log(v1);
        $(function () {
            getCodeList(v1, v2, v3, v4, v5, v6, v7);
            var element = $("#html-content-holder"); // global variable
            var getCanvas; // global variable

            $("#btn-Preview-Image").on('click', function () {
                var _str = "";
                $(".code-list .A4").each(function (i, item) {
                    //console.log($(this).data("index"));
                    html2canvas($(this), {
                        onrendered: function (canvas) {
                            //console.log(typeof(canvas))
                            //$("#previewImage").append(canvas);
                            //getCanvas = canvas;
                            var imgageData = canvas.toDataURL("image/png");
                            // Now browser starts downloading it instead of just showing it
                            var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
                            //console.log(newData);
                            var _pic = "<img src='" + newData + "' data-no="+i+"/>";
                            //console.log(_pic);
                            _str += '<img src="' + newData + '" data-no=' + i + '/>'
                            //$("#btn-Convert-Html2Image").attr("download", "your_pic_name.png").attr("href", newData);
                            $("#previewImage").prepend(_pic);
                            //console.log(_str);
                        }
                    });
                })
                setTimeout(function () {
                    console.log(_str);
                    //$("#previewImage").html(_str);
                }, 50)
            });

            $("#btn-Convert-Html2Image").on('click', function () {
                $("#previewImage img").each(function (i, item) {
                    console.log($(this))
                    var path = $(this).context;
                    //console.log(path);
                    //$(this).attr("download", "your_pic_" + i + ".png").attr("href", path);
                    //downloadImage(path);
                    //downloadFile("http://localhost:23768/", "your_pic_" + i + ".png", path);
                   // downloadFiles("your_pic_" + i + ".png", path);
                    createAndDownloadFile("your_pic_" + i + ".png", path);
                })
            });
        })
        function downloadImage(src,i) {
            var a = $("<a></a>").attr("href", src).attr("download", "your_pic_" + i + ".png").appendTo("body");

            a[0].click();
            a.remove();
        }
        function downloadFile(aLink, fileName, content) {
            console.log(aLink)
            aLink.download = fileName;
            aLink.href = "data:text/plain," + content;
        }
        function downloadFiles(fileName, content) {
            console.log(111)
            var aLink = document.createElement('a');
            var blob = new Blob([content]);
            var evt = document.createEvent("HTMLEvents");
            evt.initEvent("click", false, false);//initEvent 不加后两个参数在FF下会报错, 感谢 Barret Lee 的反馈
            aLink.download = fileName;
            aLink.href = URL.createObjectURL(blob);
            aLink.dispatchEvent(evt);
        }
        /**
 * 创建并下载文件
 * @param  {String} fileName 文件名
 * @param  {String} content  文件内容
 */
        function createAndDownloadFile(fileName, content) {
            var aTag = document.createElement('a');
            var blob = new Blob([content]);
            aTag.download = fileName;
            aTag.href = URL.createObjectURL(blob);
            aTag.click();
            URL.revokeObjectURL(blob);
        }
        function GetQueryValue(queryName) {
            var reg = new RegExp("(^|&)" + queryName + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) {
                return decodeURI(r[2]);
            } else {
                return null;
            }
        }
        function getCodeList(val1, val2, val3, val4, val5, val6, val7) {
            $.ajax({
                url: '/print/data.ashx?oper=getCodeList',
                type: 'get',
                async: true,
                data: {
                    val1: val1,
                    val2: val2,
                    val3: val3,
                    val4: val4,
                    val5: val5,
                    val6: val6,
                    val7: val7
                },
                dataType: 'json'
            }).then(function (res) {
                console.log(res);
                if (res.status == "1") {
                    var result = res.result;
                    if (result.length > 0) {
                        setJson(result);
                    }
                    else {
                        $(".code-list").html("未查询到数据");
                    }
                }
                else {
                    layer.msg('系统错误');
                    return false;
                }
            }).fail(function (res) {
                console.log('失败');
                console.log(res.responseText);
            })
        }
        function setJson(json) {
            var _str = '';
            var n = parseInt(type);
            //n = 0;
            switch (n) {
                case 0:
                    //代码块,前五个
                    var result = [];
                    for (var i = 0, len = json.length; i < len; i += 36) {
                        result.push(json.slice(i, i + 36));
                    }
                    console.log(result);
                    _str += '<div class="box1">';
                    $.each(result, function (j, jtem) {
                        _str += '<div class="A4" data-index="'+j+'">';
                        for (var k = 0; k < 4; k++) {
                            //_str += '<div class="vertical ver' + (k + 1)+ '"></div>';
                        }
                        $.each(jtem, function (i, item) {
                            _str += '<div class="box" data-index=' + i + '>'
                                + '<div class="qrcode"><span class="cnaidc" id="' + item.code + '" data-code="' + item.code + '"></span><h5>' + item.name + '</h5></div></div>'
                            if ((i + 1) % 5 == 0) {
                                //_str += '<hr />';
                            }
                        })
                        _str += '</div>';
                    })
                    _str += '</div>';
                    break;
                case 1:
                    //代码块,物品标签
                    var result = [];
                    for (var i = 0, len = json.length; i < len; i += 12) {
                        result.push(json.slice(i, i + 12));
                    }
                    console.log(result);
                    _str += '<div class="box2">';
                    $.each(result, function (j, jtem) {
                        _str += '<div class="A4" data-index="' + j + '">';
                        $.each(jtem, function (i, item) {
                            _str += '<div class="box" data-index=' + i + '><div class="inbox">'
                                + '<div class="qrcode"><span class="cnaidc" id="' + item.labelcode + '" data-code="' + item.labelcode + '"></span><h5>' + item.labelcode + '</h5></div>'
                                + '<div class="info"><h6 class="name">名称：' + item.name + '</h6><span>规格型号：' + item.spec + ' ' + item.model + '</span><p>位置：' + item.position + '</p></div></div></div>'
                            if ((i + 1) % 2 == 0) {
                                //_str += '<hr />';
                            }
                        })
                        _str += '</div>';
                    })

                    _str += '</div>';
                    break;
                case 2:
                    //代码块,位置标签
                    var result = [];
                    for (var i = 0, len = json.length; i < len; i += 30) {
                        result.push(json.slice(i, i + 30));
                    }
                    console.log(result);
                    _str += '<div class="box1">';
                    $.each(result, function (j, jtem) {
                        _str += '<div class="A4" data-index="' + j + '">';
                        for (var k = 0; k < 4; k++) {
                            //_str += '<div class="vertical ver' + (k + 1) + '"></div>';
                        }
                        $.each(jtem, function (i, item) {
                            _str += '<div class="box" data-index=' + i + '>'
                                + '<div class="qrcode"><h5>' + item.name + '</h5><span class="cnaidc" id="' + item.code + '" data-code="' + item.code + '"></span></div></div>'
                            if ((i + 1) % 5 == 0) {
                                // _str += '<hr />';
                            }
                        })
                        _str += '</div>';
                    })
                    _str += '</div>';
                    break;
                default:
                    // 默认代码块
            }

            $(".code-list").html(_str);
            //setBarCode();
            setQRCode();
        }
        function setBarCode() {
            var settings = {
                output: 'css',
                color: '#000',
                barWidth: 2,
                barHeight: 30,
                displayValue: true,
                fontOptions: "bold",
                fontSize: 16,
                moduleSize: 5,
                addQuietZone: 10
            };
            $.each($(".code-list .box .cnaidc"), function () {
                var _code = $(this).data("code");
                console.log(_code);
                $(this).barcode(_code.toString(), "code128", settings);
            })

            setTimeout(function () {
                window.print();
            }, 20)

        }
        function setQRCode() {
            $.each($(".code-list .box .cnaidc"), function () {
                var _code = $(this).data("code");
                if (!_code) {
                    return false;
                } else {
                    new QRCode(document.getElementById(_code), _code);
                }
            })
            //generateImg();//--生成图片
            setTimeout(function () {
                //window.print();
            }, 20)
        }
        function generateImg() {
            $.each($(".code-list .box"), function () {
                html2canvas($(this)).then(function (canvas) { document.body.appendChild(canvas); });
            })
            setTimeout(function () {
                //window.print();
            }, 20)
        }
        function demoFromHTML() {
            var pdf = new jsPDF('p', 'pt', 'letter')

            // source can be HTML-formatted string, or a reference
            // to an actual DOM element from which the text will be scraped.
            , source = $('#html-content-holder')[0]

            // we support special element handlers. Register them with jQuery-style 
            // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
            // There is no support for any other type of selectors 
            // (class, of compound) at this time.
            , specialElementHandlers = {
                // element with id of "bypass" - jQuery style selector
                '#bypassme': function (element, renderer) {
                    // true = "handled elsewhere, bypass text extraction"
                    return true
                }
            }

            margins = {
                top: 80,
                bottom: 60,
                left: 40,
                width: 522
            };
            // all coords and widths are in jsPDF instance's declared units
            // 'inches' in this case
            pdf.fromHTML(
                source // HTML string or DOM elem ref.
                , margins.left // x coord
                , margins.top // y coord
                , {
                    'width': margins.width // max width of content on PDF
                    , 'elementHandlers': specialElementHandlers
                },
                function (dispose) {
                    // dispose: object with X, Y of the last line add to the PDF 
                    //          this allow the insertion of new lines after html
                    pdf.save('Test.pdf');
                },
                margins
            )
        }
    </script>
</body>
</html>
